const TemplateApi = require("../config/template")
const ora = require("ora")
const inquirer = require("inquirer")
const ncp = require("ncp")
const path = require("path")
const { promisify } = require("util") // 转为promise
const { template_path } = require("../config/command")

let downloadGitRepo = require("download-git-repo") //git包下载
downloadGitRepo = promisify(downloadGitRepo)
async function LoadingCallback(fn) {

    return async function(url, msg) {
        const state = ora(msg)
        state.start()
        try {
            var Git_Template = await fn(url)
        } catch (e) {
            state.stop()
            console.log("err: ", e.message)
        }
        state.succeed()

        return Git_Template
    }
}
async function download(repo, tag) {
    const state = ora("模板搜索中......")
    const api = `skyllove/${repo}`;
    if (tag) {
        api += `#${tag}`
    }
    await downloadGitRepo(api, template_path)
    state.succeed()
    return api
}
module.exports = async function(action, param) {
    // 公共请求函数
    let CommonFun = await LoadingCallback(TemplateApi)
        // 模板请求
    let Git_Template = await CommonFun("/users/skyllove/repos", "搜索模板")
        //选择器
    if (!Git_Template) {
        console.log("模板查询失败")
        return
    }
    let arr = Git_Template = Git_Template.map(v => {
            return v.name
        })
        // 模板选择
    const { repo } = await inquirer.prompt({
            name: "repo",
            type: "list",
            message: "请选择模板",
            choices: arr
        })
        // 版本选择
    let Git_Tag = await CommonFun("/repos/skyllove/" + repo + "/tags", "版本查询")
    let tag_arr = Git_Tag.map(v => {
        return v.name
    })
    const tag = await inquirer.prompt({
        name: "repo",
        type: "list",
        message: "请选择版本",
        choices: tag_arr
    }).repo
    await download(repo, tag)
    await ncp(template_path, path.resolve(param))







}